package com.ym.core.utils.tkmybatis;

import com.ym.common.constant.BaseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.weekend.Fn;
import tk.mybatis.mapper.weekend.reflection.Reflections;

import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * 基类service
 *
 * @author: 李涛
 * @version: 2020年07月01日 17:03
 */
public abstract class BaseSVImpl<E extends BaseEntity, M extends Mapper<E>> implements IBaseSV<E> {

	@Autowired
	protected M mapper;

	protected Class<E> cls;

	/**
	 * 快速构建当前实体的select
	 *
	 * @return
	 */
	protected TK<E> Select() {
		return TK.select(cls);
	}

	/**
	 * 快速构建当前实体的select where
	 *
	 * @return
	 */
	protected TKCriteria<E, Object> SelectWhere() {
		return TK.select(cls).where();
	}

	/**
	 * 获取当前实例的class
	 */ {
		if (cls == null) {
			cls = (Class<E>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
		}
	}

	@Override
	public E selectById(Long id) {
		return mapper.selectByPrimaryKey(id);
	}

	@Override
	public <R> R selectField(Fn<E, R> fn, TK<E> queryParam) {
		queryParam.column(Reflections.fnToFieldName(fn));
		E e = mapper.selectOneByExample(queryParam);
		return fn.apply(e);
	}

	@Override
	public E selectOne(TK<E> queryParam) {
		return mapper.selectOneByExample(queryParam);
	}

	@Override
	public E selectOne(E queryParam) {
		return mapper.selectOne(queryParam);
	}

	@Override
	public List<E> selectList(TK<E> queryParam) {
		return mapper.selectByExample(queryParam);
	}

	@Override
	public List<E> selectList(E queryParam) {
		return mapper.select(queryParam);
	}

	@Override
	public List<E> selectAll() {
		return mapper.selectAll();
	}

	@Override
	public int countByParams(TK<E> queryParam) {
		return mapper.selectCountByExample(queryParam);
	}

	@Override
	public int countByParams(E queryParam) {
		return mapper.selectCount(queryParam);
	}

	@Override
	public boolean exist(TK<E> queryParam) {
		return mapper.selectCountByExample(queryParam) > 0;
	}

	@Override
	public Long insert(E param) {
		mapper.insertSelective(param);
		return param.getId();
	}

	@Override
	public int updateById(E param) {
		return mapper.updateByPrimaryKeySelective(param);
	}

	@Override
	public int updateByIds(E param, Long[] ids) {
		return mapper.updateByExampleSelective(param, SelectWhere().andIn(E::getId, ids));
	}

	@Override
	public int updateByParams(E param, TK<E> queryParam) {
		return mapper.updateByExampleSelective(param, queryParam);
	}

	@Override
	public int deleteById(Long id) {
		return mapper.deleteByPrimaryKey(id);
	}

	@Override
	public int deleteByParams(TK<E> queryParam) {
		return mapper.deleteByExample(queryParam);
	}

	@Override
	public int deleteByParams(E queryParam) {
		return mapper.delete(queryParam);
	}

	@Override
	public int deleteByIds(Long[] ids) {
		return deleteByParams(SelectWhere().andIn(E::getId, ids).end());
	}
}
